package com.thinkTank.oa.controller;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.thinkTank.oa.common.Constant;
import com.thinkTank.oa.common.SystemGlobals;
import com.thinkTank.oa.configuration.Log;
import com.thinkTank.oa.configuration.RefPid;
import com.thinkTank.oa.entity.ButtDetails;
import com.thinkTank.oa.entity.Demand;
import com.thinkTank.oa.entity.DemandData;
import com.thinkTank.oa.entity.Dictiontry;
import com.thinkTank.oa.entity.ImportDemand;
import com.thinkTank.oa.entity.Operationlog;
import com.thinkTank.oa.entity.Person;
import com.thinkTank.oa.entity.Project;
import com.thinkTank.oa.entity.Subscribe;
import com.thinkTank.oa.entity.User;
import com.thinkTank.oa.entity.UserGroup;
import com.thinkTank.oa.lucene.IsolrOperation;
import com.thinkTank.oa.lucene.LuceneDemand;
import com.thinkTank.oa.lucene.LucenePerson;
import com.thinkTank.oa.lucene.LuceneProject;
import com.thinkTank.oa.lucene.Pagination;
import com.thinkTank.oa.lucene.SolrOperation;
import com.thinkTank.oa.service.CustomerService;
import com.thinkTank.oa.service.DemandDataService;
import com.thinkTank.oa.service.DemandService;
import com.thinkTank.oa.service.DetailsService;
import com.thinkTank.oa.service.OperationlogService;
import com.thinkTank.oa.service.PersonService;
import com.thinkTank.oa.service.ProjectService;
import com.thinkTank.oa.service.SubscribeService;
import com.thinkTank.oa.service.UserGroupService;
import com.thinkTank.oa.util.ExcelUtil;
import com.thinkTank.oa.util.StrUtil;

@Controller
@RequestMapping("/demand")
public class DemandController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(DemandController.class);

    @Resource
    private DemandService demandService;
    @Resource
    private PersonService personService;
    @Resource
    private DetailsService detailsService;
    @Resource
    private ProjectService projectService;
    @Autowired
	private SubscribeService subscribeService;
    @Autowired
    private DemandDataService demandDataService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private OperationlogService operationlogService;
    @Autowired
    private UserGroupService userGroupService;
    /**
     * @date2018-11-02
     * @author dq
     * 查询用户提交的需求，项目等
     * @return
     */
    @RequestMapping("/showDemandData")
    public String showDemandData(Integer pageNo,HttpServletRequest request){
    	
    	try{
    		if(null==pageNo){
				pageNo=1;
			}
			 PageHelper.startPage(pageNo, DEFAULT_COUNT);
			 DemandData demand = new DemandData();
			 List<DemandData> demandList = demandDataService.queryAll(demand);
			 PageInfo<DemandData> pageInfo = new PageInfo<DemandData>(demandList);
			 request.setAttribute("pageInfo", pageInfo);
			 
    	}catch(Exception e){
    		
    	}
    	return "showDemandData";
    }
    
    
    private void addAttrModel(Model model) {
        // 来源
        List<Dictiontry> projecSourcetDictiontryList = getProjectSorce();
        //所有国家
        List<Dictiontry> countryDictiontryList = SystemGlobals.getInstance()
                .getDictiontryMap(Constant.DICTIONTRY_COUNTRY);
        // 所有省份
        List<Dictiontry> provinceDictiontryList = getAreaProvince();
        // 研究领域
        List<Dictiontry> researchFieldDictiontryList = getResearchField();
        // 需求类型demandType
        List<Dictiontry> demandTypeDictiontryList = SystemGlobals.getInstance()
                .getDictiontryMap(Constant.DICTIONTRY_DEMANDTYPE);
        // 需求状态
        List<Dictiontry> demandStatusDictiontryList = SystemGlobals.getInstance()
                .getDictiontryMap(Constant.DICTIONTRY_DEMANDSTATUS);

        // 专家类型
        List<Dictiontry> personTypeDictiontryList = getPersonType();
        // 人才级别
        List<Dictiontry> talentLevelDictiontryList = getTalentLevel();

        model.addAttribute("projecSourcetDictiontryList", projecSourcetDictiontryList);
        model.addAttribute("countryDictiontryList", countryDictiontryList);
        model.addAttribute("provinceDictiontryList", provinceDictiontryList);
        model.addAttribute("researchFieldDictiontryList", researchFieldDictiontryList);
        model.addAttribute("demandTypeDictiontryList", demandTypeDictiontryList);
        model.addAttribute("demandStatusDictiontryList", demandStatusDictiontryList);
        model.addAttribute("personTypeDictiontryList", personTypeDictiontryList);
        model.addAttribute("talentLevelDictiontryList", talentLevelDictiontryList);
    }

    @RequestMapping("/showAdd")
    public String showAdd(Model model) {
        addAttrModel(model);
        return "demand/showAdd";
    }

    @RequestMapping("/add")
    public String add(@Valid Demand demand, BindingResult bindingResult, Model model, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            //出错时将填写的值返回
            model.addAttribute("demand", demand);
            List<FieldError> list = bindingResult.getFieldErrors();
            list.forEach(e -> logger.error("错误字段：{}, 错误信息：{}", e.getField(), e.getDefaultMessage()));
            list.forEach(e -> model.addAttribute(e.getField(), e.getDefaultMessage()));
            return showAdd(model);
        }
        setDemandAttr(demand, request);
        demandService.add(demand);
        addDemandIsolr(demand, new SolrOperation<>());
        return "redirect:/demand/showDetail?demandId="+demand.getPid();
    }

    private void setDemandAttr(Demand demand, HttpServletRequest request) {
        demand.setPid(StrUtil.getUUID32());
        demand.setCollectPersonId(getUserInfoBySession(request).getUserId());
        demand.setEntryTime(StrUtil.getCurrentDateTime());
        demand.setDemandTypeInteger(StrUtil.stringByByte(demand.getDemandType()));
        demand.setResearchFieldInteger(StrUtil.stringByByte(demand.getResearchField()));
    }

    @RequestMapping("/showUpdate")
    public String showUpdate(String demandId, Model model) {
        Demand demand = demandService.getById(demandId);
        prepare(model, demand);
        return "demand/showUpdate";
    }

    private void prepare(Model model, Demand demand) {
        String[] researchFieldArr = StrUtil.byteToString(demand.getResearchField()).split(",");
        String[] demandTypedArr = StrUtil.byteToString(demand.getDemandType()).split(",");
        
        areaModel(model, demand.getArea(), demand.getDomesticOrForeign());
        addAttrModel(model);
        model.addAttribute("demand", demand);
        model.addAttribute("researchFieldArr", researchFieldArr);
        model.addAttribute("demandTypedArr", demandTypedArr);
    }

    @Log("修改需求")//查询的是时候以这个为依据查询，所以不可更改
    @RequestMapping("/update")
    public String update(@RefPid @Valid Demand demand, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            List<FieldError> list = bindingResult.getFieldErrors();
            list.forEach(e -> logger.error("错误字段：{}, 错误信息：{}", e.getField(), e.getDefaultMessage()));
            list.forEach(e -> model.addAttribute(e.getField(), e.getDefaultMessage()));
            return showUpdate(demand.getPid(), model);
        }
        demand.setUpdateTime(StrUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
        demand.setDemandTypeInteger(StrUtil.stringByByte(demand.getDemandType()));
        demand.setResearchFieldInteger(StrUtil.stringByByte(demand.getResearchField()));
        demandService.update(demand);
        addAttrModel(model);
        updateDemandIsolr(demand, new SolrOperation<>(), false);
        return "redirect:/demand/showDetail?demandId="+demand.getPid();
    }

    @RequestMapping("/showAddContact")
    public String showAddContact(Model model, String demandId) {
        addAttrModel(model);
        return "demand/showAddContact";
    }

    @RequestMapping("/addContact")
    public String addContact(@Valid Person person, BindingResult bindingResult, String demandId,
            HttpServletRequest request, Model model, MultipartFile file) {
        if (bindingResult.hasErrors()) {
            List<FieldError> list = bindingResult.getFieldErrors();
            list.forEach(e -> logger.error("错误字段：{}, 错误信息：{}", e.getField(), e.getDefaultMessage()));
            list.forEach(e -> model.addAttribute(e.getField(), e.getDefaultMessage()));
            return showAddContact(model, demandId);
        }
        if (!hasContact(person)) {
            model.addAttribute("fixedPhone", "至少填写一种联系方式");
            return showAddContact(model, demandId);
        }
        setPersonAttr(person, request);
        Demand demand = demandService.getById(demandId);
        personService.addContact(person, demand, file);
        addPersonIsolr(person, new SolrOperation<>());
        updateDemandIsolr(demand, new SolrOperation<>(), true);
        return "redirect:/demand/showQuery";
    }

    private void setPersonAttr(Person person, HttpServletRequest request) {
        person.setPid(StrUtil.getUUID32());
        person.setCollectPersonId(getUserInfoBySession(request).getUserId());
        person.setEntryTime(StrUtil.getCurrentDateTime());
        person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
        if (StringUtil.isNotEmpty(person.getTalentLevel()))
            person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
    }
    
    @RequestMapping("/showUpdateContact")
    public String showUpdateContact(Model model, String demandContactId, HttpServletRequest request) {
        if (!demandContactId.matches("[a-z0-9]{32}")) {
            model.addAttribute("projectContactNotExists", "没有关联的联系人，不能修改");
            return showQuery(model, 1, request);
        }
        Person person = personService.getById(demandContactId);
        String[] researchFieldArr = StrUtil.byteToString(person.getResearchField()).split(",");
        String[] talentLevelArr = new String[0];
        if (StringUtil.isNotEmpty(person.getTalentLevel()))
            talentLevelArr = StrUtil.byteToString(person.getTalentLevel()).split(",");
        areaModel(model, person.getArea(), person.getDomesticOrForeign());
        addAttrModel(model);
        model.addAttribute("person", person);
        model.addAttribute("researchFieldArr", researchFieldArr);
        model.addAttribute("talentLevelArr", talentLevelArr);
        return "demand/showUpdateContact";
    }
    
    /**
     * 修改联系人
     * @author pdz
     * @date 2018年8月22日
     * @param person
     * @param bindingResult
     * @param demandContactId
     * @param model
     * @return
     */
    @RequestMapping("/updateContact")
    public String updateContact(@Valid Person person, BindingResult bindingResult, Model model, MultipartFile file, 
    		HttpServletRequest request, String demandId) {
        if (bindingResult.hasErrors()) {
            List<FieldError> list = bindingResult.getFieldErrors();
            list.forEach(e -> logger.error("错误字段：{}, 错误信息：{}", e.getField(), e.getDefaultMessage()));
            list.forEach(e -> model.addAttribute(e.getField(), e.getDefaultMessage()));
            return showUpdateContact(model, person.getPid(), request);
        }
        String oldName = personService.getById(person.getPid()).getName();
        if (!hasContact(person)) {
            model.addAttribute("fixedPhone", "至少填写一种联系方式");
            return showUpdateContact(model, person.getPid(), request);
        } else if (!oldName.equals(person.getName())) {
        	person.setExpertNumber(null);
        	return addContact(person, bindingResult, demandId, request, model, file);
        }
        person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
        if (StringUtil.isNotEmpty(person.getTalentLevel()))
            person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
        personService.update(person, file);
        updatePersonIsolr(person, new SolrOperation<>(), false);
        return "redirect:/demand/showQuery";
    }
    
    @RequestMapping("/showQuery")
    public String showQuery(Model model, @RequestParam(defaultValue = "1") int pageNo, HttpServletRequest request) {
        pageInfo(model, pageNo, new Demand(), request);
        return "demand/showQuery";
    }
    
    /**
     * 根据传进来的dem查询分页， 会将查到pageInfo和一些需要的值放到model中
     * @author pdz
     * @date 2018年8月29日
     * @param model
     * @param pageNo
     * @param dem 如果传进来的是属性都为空的dem，就是全查询，否则就是条件查询
     * @return
     */
    private PageInfo<Demand> pageInfo(Model model, int pageNo, Demand dem, HttpServletRequest request) {
        PageHelper.startPage(pageNo, DEFAULT_COUNT);
        List<Demand> list = demandService.queryAll(dem);
        PageInfo<Demand> pageInfo = new PageInfo<Demand>(list);
        pageInfo.getList().forEach(demand -> setDemandWorth(demand));
        //查询已经关注的
        Subscribe subscribe = new Subscribe();
        subscribe.setSubType(2);//关注类型为项目
        subscribe.setUserid(getUserId(request));
        List<Subscribe> subList = subscribeService.queryAll(subscribe);
        List<String> subDemandIdList = subList.stream().map(Subscribe::getTypeObject).collect(Collectors.toList());
        model.addAttribute("subDemandIdList", subDemandIdList);
        addAttrModel(model);
        model.addAttribute(pageInfo);
        return pageInfo;
    }

	@RequestMapping("/showConditionQuery")
    public String showConditionQuery(Model model, Demand demand, String searchKeyword, @RequestParam(defaultValue = "1") int pageNo, HttpServletRequest request) {
        searchPageInfo(model, demand, searchKeyword, pageNo, request);
        return "demand/showQuery";
    }
    
    /**
     * 有条件的搜索，会把传进来的查询条件放到model中，以便在页面显示，得到的分页以及一些展示属性也会放在model中
     * @author pdz
     * @date 2018年8月29日
     * @param demand
     * @param searchKeyword
     * @param pageNo
     * @return
     */
    private PageInfo<Demand> searchPageInfo(Model model, Demand demand, String searchKeyword, int pageNo, HttpServletRequest request) {
        if (StringUtil.isNotEmpty(searchKeyword)) {
        	searchKeyword = searchKeyword.trim();
            if (searchKeyword.matches("D\\d{6,}"))
                demand.setDemandNumber(Integer.parseInt(searchKeyword.replaceFirst("D", "")));
            else {
            	switch (demand.getTag()) {
            	case 1:
            		demand.setDemandContactName(searchKeyword);
            		break;
            	case 2:
            		demand.setDemandUnit(searchKeyword);
            		break;
            	default:
            		demand.setDemandName(searchKeyword);
            		break;
            	}
            }
        }
        String[] researchFieldArr = null;
        String[] demandTypedArr = null;
        if (StringUtil.isNotEmpty(demand.getDemandType())) {
            demandTypedArr = demand.getDemandType().split(",");
            demand.setDemandTypeNumber(demandTypedArr.length);
            demand.setDemandTypeInteger(StrUtil.stringByByte(demand.getDemandType()));
        }
        if (StringUtil.isNotEmpty(demand.getResearchField())) {
            researchFieldArr = demand.getResearchField().split(",");
            demand.setResearchFieldNumber(researchFieldArr.length);
            demand.setResearchFieldInteger(StrUtil.stringByByte(demand.getResearchField()));
        }
        PageInfo<Demand> pageInfo = pageInfo(model, pageNo, demand, request);
        if (demand.getArea() != null)
            areaModel(model, demand.getArea(), demand.getDomesticOrForeign());
        model.addAttribute("searchKeyword", searchKeyword);
        model.addAttribute("demand", demand);
        model.addAttribute("researchFieldArr", researchFieldArr);
        model.addAttribute("demandTypedArr", demandTypedArr);
        return pageInfo;
    }
    
    
	@RequestMapping("/showProjectMatchedDemand")
    public String showProjectMatchedDemand(Model model, Project project, HttpServletRequest request) {
        searchMatchedDemand(model, null, null, null, null, 1, project.getPid(), request);
        return "demand/showProjectMatchedDemand";
    }
    
    /**
     * 搜索项目匹配的需求
     * @author pdz
     * @date 2018年8月28日
     * @param model
     * @param demand 用于搜索 
     * @param searchKeyword 用于搜索
     * @param pageNo
     * @param projectId
     * @return
     */
	@RequestMapping("/searchMatchedDemand")
    public String searchMatchedDemand(Model model, String researchField, String area, String searchKeyword, Integer domesticOrForeign,
    		@RequestParam(defaultValue = "1") int pageNo, String projectId, HttpServletRequest request) {
    	
    	String researchFieldWorth = StringUtil.isEmpty(researchField) ? null : getDicCheckboxWorth(StrUtil.stringByByte(researchField).toString(), Constant.DICTIONTRY_DEMANDFIELD);
    	String areaWorth = StringUtil.isEmpty(area) ? null : getAreaWorth(area, domesticOrForeign);
    	Project project = projectService.getById(projectId);
        Pagination pagination = new SolrOperation<>().queryList(pageNo, DEFAULT_COUNT, 4, projectId, researchFieldWorth, areaWorth, searchKeyword);
        //根据projectid查询对接详情，然后筛选出已经对接过的demand
        ButtDetails buttDetails = new ButtDetails();
        buttDetails.setButtPersonId(getUserId(request));
        buttDetails.setProjectNumber(projectId);
        buttDetails.setFuture(1);
        buttDetails.setDemandNumberEmpty(false);
        List<ButtDetails> demandDetailList = detailsService.findButtDetails(buttDetails);
        List<String> buttedDemandIdList = demandDetailList.stream().map(ButtDetails::getDemandNumber).collect(Collectors.toList());
		String[] researchFieldArr = StringUtil.isNotEmpty(researchField) ? researchField.split(",") : new String[0];
        if (StringUtil.isNotEmpty(area))
            areaModel(model, area, domesticOrForeign);
        addAttrModel(model);
        model.addAttribute("researchFieldArr", researchFieldArr);
        model.addAttribute("pageInfo", pagination);
        model.addAttribute("project", project);
        model.addAttribute("buttedDemandIdList", buttedDemandIdList);
        model.addAttribute("domesticOrForeign", domesticOrForeign);
        return "demand/showProjectMatchedDemand";
    }
    
    @RequestMapping("/projectMatchDemand")
    @ResponseBody
    public String projectMatchDemand(String demandId, Demand demand, String projectId, Project project, HttpServletRequest request) {
        demand.setPid(demandId);
        project.setPid(projectId);
        detailsService.addFirstButtDetails(project, demand, null, null, null, getUserId(request));
        return "success";
    }
    
    /**
     * 显示需求已经匹配的项目
     * @param demandId
     * @param buttSta
     * @param pageNo
     * @return
     */
    @RequestMapping("/showProjectButtDetail")
    public String showProjectButtDetail(Demand demand, HttpServletRequest request, Model model, Integer buttSta, 
    		@RequestParam(defaultValue = "1") int pageNo, String customerId) {
        PageHelper.startPage(pageNo, DEFAULT_COUNT);
        List<ButtDetails> buttProjectList = queryProjectButtDetail(demand.getPid(), request, buttSta);
        PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(buttProjectList);
        List<Dictiontry> buttStatusList=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
        model.addAttribute("buttStatusList", buttStatusList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("demand", demand);
        model.addAttribute("customerId", customerId);
        model.addAttribute("buttSta", buttSta != null ? buttSta.toString() : "");
        //自己已经更新过的对接详情
        List<String> updatedButtProjectIdList = queryButtProject(demand.getPid(), null, bd -> bd.setFuture(0), null)
        		.stream().map(ButtDetails::getProjectNumber).distinct().collect(Collectors.toList());
        List<String> undoButtIdList = pageInfo.getList().stream().filter(bd -> bd.getButtPersonId().equals(getUserId(request)))
        	.filter(bd -> !updatedButtProjectIdList.contains(bd.getProjectNumber())).map(ButtDetails::getPid).collect(Collectors.toList());
        model.addAttribute("undoButtIdList", undoButtIdList);
        return "demand/showProjectButtDetail";
    }

    /**
     * 根据需求id查询项目对接详情
     * @param demandId
     * @param buttSta 为空查询所有状态
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryProjectButtDetail")
	public List<ButtDetails> queryProjectButtDetail(String demandId, HttpServletRequest request, Integer buttSta) {
		List<ButtDetails> buttProjectList = queryButtProject(demandId, buttSta, bd -> bd.setFuture(1), null);
        buttProjectList.forEach(bd -> bd.setButtStatusWorth(getButtStatusWorth(bd.getButtStatus())));
        buttProjectList.forEach(bd -> bd.setRemark2(bd.getDemandName() + "<br>" + bd.getProjectName()));
		return buttProjectList;
	}

    /**
     * 根据某一个需求查询所匹配的项目
     * @author pdz
     * @date 2018年10月29日
     * @param demandId 
     * @param buttSta 对接状态，为空查询所有状态
     * @param futureAction 不为null时设置future
     * @param buttPersonAction 不为null时设置buttPerson
     * @return
     */
	private List<ButtDetails> queryButtProject(String demandId, Integer buttSta, Consumer<ButtDetails> futureAction, Consumer<ButtDetails> buttPersonAction) {
		ButtDetails buttDetails = new ButtDetails();
        buttDetails.setDemandNumber(demandId);
        if (futureAction != null)
        	futureAction.accept(buttDetails);
        if (buttPersonAction != null)
        	buttPersonAction.accept(buttDetails);
        buttDetails.setButtStatus(buttSta);
        buttDetails.setProjectNumberEmpty(false);
        return detailsService.findButtDetails(buttDetails);
	}
    
    /**
     * 下载需求已经匹配的项目
     * @author pdz
     * @date 2018年10月29日
     */
	@RequestMapping("/downButtedProject")
    public void downButtedProject(String demandId, HttpServletRequest request, HttpServletResponse response) {
    	List<String> tagList = Arrays.asList("项目ID", "项目名称", "项目类型", "项目状态", "项目简介", "所属领域", "项目联系人", "手机", "邮箱");
    	List<Project> buttedProjectList = demandService.queryButtedProject(demandId);
    	List<List<String>> contentLists = buttedProjectList.stream().map(pro -> createContentList(pro)).collect(Collectors.toList());
    	File excelFile = ExcelUtil.writeExcel(tagList, contentLists, StrUtil.getCurrentDateTime("yyyyMMddHHmmss") + "-demand-butted-projects.xls");
    	try {
			ExcelUtil.downLoad(request, excelFile, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    private List<String> createContentList(Project pro) {
    	//可能没有联系人
    	if (pro.getPer() == null)
    		pro.setPer(new Person());
    	return Arrays.asList("R"+pro.getProjectNumber(), pro.getProjectName(), getDicCheckboxWorth(pro.getProjectType(), Constant.DICTIONTRY_PROJECTTYPE),
    			getDicSingleWorth(pro.getProjectStatus(), Constant.DICTIONTRY_PROJECTSTATUS), pro.getIntroduction(),
    			getDicCheckboxWorth(pro.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD),
    			pro.getPer().getName(), pro.getPer().getTell(), pro.getPer().getEmail());
	}

	@RequestMapping("/deleteProjectButt")
    public String deleteProjectButt(Demand demand, HttpServletRequest request, Model model, Integer buttSta, 
    		@RequestParam(defaultValue = "1") int pageNo, String customerId, String buttId) {
    	detailsService.delete(buttId);
    	return showProjectButtDetail(demand, request, model, buttSta, pageNo, customerId);
    }
    
    /**
     * 需求已经匹配的专家
     * @param demandId
     * @param request
     * @param model
     * @param buttSta
     * @param pageNo
     * @return
     */
    @RequestMapping("/showExpertButtDetail")
    public String showExpertButtDetail(Demand demand, HttpServletRequest request, Model model, Integer buttSta, 
    		@RequestParam(defaultValue = "1") int pageNo, String customerId) {
        PageHelper.startPage(pageNo, DEFAULT_COUNT);
        List<ButtDetails> demandDetailList = queryExpertButtDetail(demand.getPid(), request, buttSta);
        PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(demandDetailList);
        List<Dictiontry> buttStatusList=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
        model.addAttribute("buttStatusList", buttStatusList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("demand", demand);
        model.addAttribute("customerId", customerId);
        model.addAttribute("buttSta", buttSta != null ? buttSta.toString() : "");
        //更新过的对接详情
        List<String> updatedExpertIdList = queryButtExpert(demand.getPid(), null, bd -> bd.setFuture(0), null)
        	.stream().map(ButtDetails::getExpertNumber).collect(Collectors.toList());
        List<String> undoButtIdList = pageInfo.getList().stream().filter(bd -> bd.getButtPersonId().equals(getUserId(request)))
        	.filter(bd -> !updatedExpertIdList.contains(bd.getExpertNumber())).map(ButtDetails::getPid).collect(Collectors.toList());
        model.addAttribute("undoButtIdList", undoButtIdList);
        return "demand/showExpertButtDetail";
    }

    @ResponseBody
    @RequestMapping("/queryExpertButtDetail")
	public List<ButtDetails> queryExpertButtDetail(String demandId, HttpServletRequest request, Integer buttSta) {
		List<ButtDetails> expertButtList = queryButtExpert(demandId, buttSta, bd -> bd.setFuture(1), null);
        expertButtList.forEach(bd -> bd.setButtStatusWorth(getButtStatusWorth(bd.getButtStatus())));
        expertButtList.forEach(bd -> bd.setRemark2(bd.getDemandName() + "<br>" + bd.getExpertName()));
		return expertButtList;
	}

	private List<ButtDetails> queryButtExpert(String demandId, Integer buttSta, Consumer<ButtDetails> futureAction, Consumer<ButtDetails> buttPersonAction) {
		ButtDetails buttDetails = new ButtDetails();
        buttDetails.setDemandNumber(demandId);
        if (futureAction != null)
        	futureAction.accept(buttDetails);
        if (buttPersonAction != null)
        	buttPersonAction.accept(buttDetails);
        buttDetails.setButtStatus(buttSta);
        buttDetails.setExpertNumberEmpty(false);
        List<ButtDetails> expertButtList = detailsService.findButtDetails(buttDetails);
		return expertButtList;
	}
    
    @RequestMapping("/deleteExpertButt")
    public String deleteExpertButt(Demand demand, HttpServletRequest request, Model model, Integer buttSta, 
    		@RequestParam(defaultValue = "1") int pageNo, String customerId, String buttId) {
    	detailsService.delete(buttId);
    	return showExpertButtDetail(demand, request, model, buttSta, pageNo, customerId);
    }
    
    @SuppressWarnings("unchecked")
    @ResponseBody
	@RequestMapping("/notButtProject")
    public List<LuceneProject> notButtProject(String demandId, HttpServletRequest request) {
    	Pagination pagination = new SolrOperation<>().queryList(1, 10, 6, demandId);
    	List<LuceneProject> list = pagination.getList();
    	List<ButtDetails> projectButtDetailList = queryProjectButtDetail(demandId, request, null);
    	//将已经匹配的projectId设为null，在页面判断
    	list.stream().filter(lp -> projectButtDetailList.stream().map(ButtDetails::getProjectNumber).anyMatch(proId -> proId.equals(lp.getProjectId())))
    		.forEach(lp -> lp.setProjectId(null));
    	return list;
    }
    
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/notButtExpert")
    public List<LucenePerson> notButtExpert(String demandId, HttpServletRequest request) {
    	Pagination pagination = new SolrOperation<>().queryList(1, 10, 7, demandId);
    	List<LucenePerson> list = pagination.getList();
    	List<ButtDetails> expertButtDetailList = queryExpertButtDetail(demandId, request, null);
    	//将已经匹配的expertId设为null，在页面判断
    	list.stream().filter(lp -> expertButtDetailList.stream().map(ButtDetails::getExpertNumber).anyMatch(perId -> perId.equals(lp.getExpertId())))
    		.forEach(lp -> lp.setExpertId(null));
    	return list;
    }
    
    /**
     * 导入需求，需求名称相同的应该不要导入
     * @author pdz
     * @date 2018年9月6日
     * @param model
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/importDemand")
    public void importDemand(Model model, MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        if (file != null) {
            try(InputStream in = file.getInputStream()) {
                List<ImportDemand> importDemandList = ExcelUtil.readImportDemandList(in);
                List<String> fullnameList = importDemandList.stream().map(ImportDemand::getDemand)
                		.map(Demand::getCollectPersonId).distinct().collect(Collectors.toList());
                List<User> userList = userService.queryInFullname(fullnameList);
                Set<String> demandNameSet = demandService.queryAll(new Demand()).stream().map(Demand::getDemandName).collect(Collectors.toSet());
                List<String> tagList = Arrays.asList("需求ID", "需求名称", "专家ID", "专家姓名");
                List<List<String>> contentLists = new ArrayList<>(importDemandList.size());
                //同名的需求不导入
                importDemandList.stream().filter(id -> !demandNameSet.contains(id.getDemand().getDemandName()))
                	.forEach(id -> importData(id, userList, contentLists, request));
                File excelFile = ExcelUtil.writeExcel(tagList, contentLists, "back.xls");
                ExcelUtil.downLoad(request, excelFile, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void importData(ImportDemand id, List<User> userList, List<List<String>> contentLists, HttpServletRequest request) {
        Demand demand = id.getDemand();
        String collectPersonId = userList.stream().filter(user -> user.getFullName().equals(demand.getCollectPersonId())).findAny().map(User::getPid).get();
        setDemandAttr(demand, request);
        Person person = id.getPerson();
        setPersonAttr(person, request);
        demand.setCollectPersonId(collectPersonId);
        person.setCollectPersonId(collectPersonId);
        
        //添加索引
//        addDemandIsolr(demand, new SolrOperation<>());
//        addPersonIsolr(person, new SolrOperation<>());
        demandService.importData(demand, dem -> personService.addContact(person, dem, null));
        List<String> list = Arrays.asList("D"+demand.getDemandNumber(), demand.getDemandName(), "E"+person.getExpertNumber(), person.getName());
        contentLists.add(list);
    }
    
	@RequestMapping("/showDetail")
    public String showDetail(String demandId, Model model, String projectId, Integer lookExpert, String expertId, String lookPwd, HttpServletRequest request) {
        Demand demand = demandService.getById(demandId);
        setDemandWorth(demand);
        model.addAttribute("demand", demand);
        model.addAttribute("collectPersonName", userService.getById(demand.getCollectPersonId()).getFullName());
        
        //查询联系人信息
        Person person = new Person();
        if(StringUtil.isNotEmpty(demand.getDemandContactId())) {
	        person = personService.findPersonByPid(demand.getDemandContactId());
	    	person.setSourceWorth(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
			person.setTypeWorth(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
			person.setResearchField(getDicCheckboxWorth(person.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
			if (StringUtil.isNotEmpty(person.getTalentLevel())) {
				person.setTalentLevel(getDicCheckboxWorth(person.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
			}
			person.setAreaWorth(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
        }
        model.addAttribute("person",person);
        if (StringUtil.isNotEmpty(projectId)) {
        	ButtDetails queryButt = new ButtDetails();
        	queryButt.setButtPersonId(getUserId(request));
        	queryButt.setFuture(1);
        	queryButt.setDemandNumber(demandId);
        	queryButt.setProjectNumber(projectId);
        	List<ButtDetails> buttDetailList = detailsService.findButtDetails(queryButt);
        	model.addAttribute("buttDetailList", buttDetailList);
        	model.addAttribute("project", projectService.getById(projectId));
        }

        //lookExpert为1表示要查看联系方式
        if (lookExpert != null && lookExpert.equals(1)) 
        	checkLookExpert(expertId, lookPwd, request);
        return "demand/showDetail";
    }

    /**
     * 将worth值设置给demand，分别有来源，状态，类型，领域，地区和收录人，来源设置给sourceWorth属性，状态设置给demandStatusWorth属性，其他的设置给属性本身
     * @author pdz
     * @date 2018年11月6日
     * @param demand
     */
	private void setDemandWorth(Demand demand) {
		demand.setSourceWorth(getDicSingleWorth(demand.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
        demand.setDemandStatusWorth(getDicSingleWorth(demand.getDemandStatus(), Constant.DICTIONTRY_DEMANDSTATUS));
        demand.setDemandType(getDicCheckboxWorth(demand.getDemandType(), Constant.DICTIONTRY_DEMANDTYPE));
        demand.setResearchField(getDicCheckboxWorth(demand.getResearchField(), Constant.DICTIONTRY_DEMANDFIELD));
        demand.setAreaWorth(getAreaWorth(demand.getArea(), demand.getDomesticOrForeign()));
	}
    
    /**
     * 添加demand索引
     * @param demand
     * @param isolr
     * @return
     */
	private boolean addDemandIsolr(Demand demand, IsolrOperation<LuceneDemand> isolr) {
    	LuceneDemand luceneDemand = luceneDemandConversion(demand);
    	ArrayList<LuceneDemand> list = new ArrayList<>();
    	list.add(luceneDemand);
    	return isolr.add("demand", list);
    }
    
	/**
	 * 更新demand索引
	 * @param demand
	 * @param isolr
	 * @return
	 */
    private boolean updateDemandIsolr(Demand demand, IsolrOperation<LuceneDemand> isolr, boolean fromDB) {
    	if (fromDB) {
    		demand.setDemandTypeInteger(Integer.parseInt(demand.getDemandType()));
    		demand.setResearchFieldInteger(Integer.parseInt(demand.getResearchField()));
    	}
    	LuceneDemand luceneDemand = luceneDemandConversion(demand);
    	return isolr.update("demand", luceneDemand);
    }
    
    /**
     * 需求来源使用的项目来源
     * @param demand
     * @return
     */
    private LuceneDemand luceneDemandConversion(Demand demand) {
    	LuceneDemand luceneDemand = new LuceneDemand();
    	luceneDemand.setDemandId(demand.getPid());
    	if (demand.getDemandNumber() != null)
    		luceneDemand.setDemandNumber("D"+demand.getDemandNumber());
    	luceneDemand.setSource(getDicSingleWorth(demand.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
    	luceneDemand.setSourceRemark(demand.getSourceRemark());
    	String demandTypeWorth = getDicCheckboxWorth(demand.getDemandTypeInteger().toString(), Constant.DICTIONTRY_DEMANDTYPE);
    	luceneDemand.setDemandType(Stream.of(demandTypeWorth.split(",")).collect(Collectors.toList()));
    	String researchFieldWorth = getDicCheckboxWorth(demand.getResearchFieldInteger().toString(), Constant.DICTIONTRY_DEMANDFIELD);
    	luceneDemand.setResearchField(Stream.of(researchFieldWorth.split(",")).collect(Collectors.toList()));
    	luceneDemand.setArea(getAreaWorth(demand.getArea(), demand.getDomesticOrForeign()));
    	luceneDemand.setDemandName(demand.getDemandName());
    	luceneDemand.setDemandStatus(getDicSingleWorth(demand.getDemandStatus(), Constant.DICTIONTRY_DEMANDSTATUS));
    	luceneDemand.setDemandContent(demand.getDemandContent());
    	luceneDemand.setDemandContactId(demand.getDemandContactId());
    	String demandContactName = StringUtil.isEmpty(demand.getDemandContactId()) ? null : personService.getById(demand.getDemandContactId()).getName();
    	luceneDemand.setDemandContactName(demandContactName);
    	return luceneDemand;
    }
    
    private boolean addPersonIsolr(Person person, IsolrOperation<LucenePerson> isolr) {
    	LucenePerson lucenePerson = lucenePersonConversion(person);
    	List<LucenePerson> list = new ArrayList<>();
    	list.add(lucenePerson);
    	return isolr.add("person", list);
    }
    
    private boolean updatePersonIsolr(Person person, IsolrOperation<LucenePerson> isolr, boolean fromDB) {
    	if (fromDB) {
    		person.setResearchFieldInteger(Integer.parseInt(person.getResearchField()));
    		if (StringUtil.isNotEmpty(person.getTalentLevel()))
    			person.setTalentLevelInteger(Integer.parseInt(person.getTalentLevel()));
    	}
    	LucenePerson lucenePerson = lucenePersonConversion(person);
    	return isolr.update("person", lucenePerson);
    }
    
    private LucenePerson lucenePersonConversion(Person person) {
    	LucenePerson lp = new LucenePerson();
    	lp.setExpertId(person.getPid());
    	if (person.getExpertNumber() != null)
    		lp.setExpertNumber("E"+person.getExpertNumber());
    	lp.setSource(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
    	lp.setType(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
    	String researchFieldWorth = getDicCheckboxWorth(person.getResearchFieldInteger().toString(), Constant.DICTIONTRY_PROJECTFIELD);
    	lp.setResearchField(Stream.of(researchFieldWorth.split(",")).collect(Collectors.toList()));
    	lp.setArea(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
    	if(StringUtil.isNotEmpty(person.getTalentLevel())){
    		String talentLevelWorth = getDicCheckboxWorth(person.getTalentLevelInteger().toString(), Constant.DICTIONTRY_TALENTLEVEL);
    		lp.setTalentLevel(Stream.of(talentLevelWorth.split(",")).collect(Collectors.toList()));
    	}
    	lp.setName(person.getName());
    	lp.setSchoolAndMajor(person.getSchoolAndMajor());
    	lp.setUnit(person.getUnit());
    	lp.setTitle(person.getTitle());
    	lp.setProfessionaField(person.getProfessionaField());
    	lp.setEducation(person.getEducation());
    	lp.setWorkExp(person.getWorkExp());
    	lp.setHonorAward(person.getHonorAward());
    	lp.setTechnica(person.getTechnica());
    	return lp;
	}
    
    /**
     * 添加联系人有弹出框，然后选择了修改就执行该方法
     * @author pdz
     * @date 2018年10月29日
     * @param projectId
     * @param demandContactId
     * @return
     */
    @RequestMapping("/showLinkUpdateContact")
    public String showLinkUpdateContact(Model model, HttpServletRequest request, String demandId, String demandContactId) {
    	return showUpdateContact(model, demandContactId, request);
    }
    
    /**
     * 先修改联系人然后直接关联
     * @author pdz
     * @date 2018年10月29日
     * @param person
     * @param projectId
     * @return
     */
    @RequestMapping("/linkUpdateContact")
    public String linkUpdateContact(Person person, BindingResult bindingResult, Model model, MultipartFile file, HttpServletRequest request, String demandId) {
    	updateContact(person, bindingResult, model, file, request, demandId);
    	return linkContact(person.getPid(), demandId);
    }
    
    @RequestMapping("/linkContact")
    public String linkContact(String personId, String demandId) {
    	Demand demand = demandService.getById(demandId);
    	demand.setDemandContactId(personId);
    	demandService.updateDemandContact(demand);
    	updateDemandIsolr(demand, new SolrOperation<>(), true);
    	return "redirect:/demand/showDetail?demandId="+demandId;
    }
    
    @RequestMapping("/statistics")
	public String statistics(Model model) {
    	LocalDate now = LocalDate.now();
		String endDate = now.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
		String beginDate = now.minusDays(7).format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
		return "redirect:/demand/queryStatistics?beginDate="+beginDate+"&endDate="+endDate;
	}
	
	/**
	 * 通过时间搜索统计
	 * @author pdz
	 * @date 2018年11月5日
	 */
	@RequestMapping("/queryStatistics")
	public String queryStatistics(String beginDate, String endDate, Model model, HttpServletRequest request) {
		//假设身份为组长查询获取所属的所有组
		UserGroup userGroup = new UserGroup().setUserId(getUserId(request)).setPosition(UserGroup.GROUP_LEADER);
		List<Integer> groupNameIdList = userGroupService.queryAll(userGroup).stream().map(UserGroup::getGroupNameId).collect(Collectors.toList());
		//查询所有组的所有成员
		final List<String> userIdList = new ArrayList<>(); 
		if (groupNameIdList != null && !groupNameIdList.isEmpty()) {
			userGroup = new UserGroup().setGroupNameIdList(groupNameIdList);
			List<String> list = userGroupService.queryAll(userGroup).stream().map(UserGroup::getUserId).collect(Collectors.toList());
			userIdList.addAll(list);
		}
		List<Map<String, String>> mapList_pro = projectService.statisticsCount(beginDate, endDate);
		List<Map<String, String>> mapList_dem = demandService.statisticsCount(beginDate, endDate);
		List<Map<String, String>> mapList_cus = customerService.statisticsCount(beginDate, endDate);
		List<Map<String, String>> mapList_per = personService.statisticsCount(beginDate, endDate);
		List<Map<String, String>> mapList_butt = detailsService.statisticsCount(beginDate, endDate);
		Map<String,String[]> map = new HashMap<>();
		List<List<Map<String, String>>> list = Arrays.asList(mapList_pro, mapList_dem, mapList_cus, mapList_per, mapList_butt);
		IntStream.range(0, list.size()).forEach(i -> fill(map, list, i));
		//修改统计
		List<String> operaList = Arrays.asList("修改项目", "修改需求", "修改客户", "修改专家", "修改对接详情");
		Operationlog operationlog = new Operationlog(beginDate, endDate, operaList);
		List<Operationlog> operaLogList = operationlogService.queryAll(operationlog);
		Map<String, Map<String, List<Operationlog>>> gmap = operaLogList.stream().collect(Collectors.groupingBy(Operationlog::getUserId, Collectors.groupingBy(Operationlog::getOperation)));
		Map<String,String[]> map1 = new HashMap<>();
		gmap.keySet().forEach(key -> {
			String[] arr = new String[operaList.size()+2];
			Map<String, List<Operationlog>> opmap = gmap.get(key);
			IntStream.range(0, operaList.size()).forEach(i -> {
				List<Operationlog> gopList = opmap.get(operaList.get(i));
				if (gopList != null && !gopList.isEmpty()) {
					arr[0] = gopList.get(0).getUsername();
					arr[i+2] = String.valueOf(gopList.size());
				}
			});
			map1.put(key, arr);
		});
		map.values().stream().forEach(arr -> IntStream.range(2, arr.length).forEach(i -> arr[i] = (StringUtil.isEmpty(arr[i]) ? "0" : arr[i]) + "-0"));
		map1.values().stream().forEach(arr -> IntStream.range(2, arr.length).forEach(i -> arr[i] = "0-" + (StringUtil.isEmpty(arr[i]) ? "0" : arr[i])));
		map1.forEach((key1, arr1) -> {
			if (map.containsKey(key1)) {
				String[] arr = map.get(key1);
				IntStream.range(2, arr1.length).forEach(i -> arr1[i] = arr[i].split("-")[0] + "-" + arr1[i].split("-")[1]);
			}
			map.put(key1, arr1);
		});
		map.values().stream().forEach(arr -> {
			int num = Stream.of(arr).skip(2).map(numberStr -> numberStr.split("-")[0]).mapToInt(Integer::parseInt).sum();
			int num1 = Stream.of(arr).skip(2).map(numberStr -> numberStr.split("-")[1]).mapToInt(Integer::parseInt).sum();
			arr[1] = num + "/" + num1;
		});
		List<String> routeList = Arrays.asList("project", "demand", "customer", "person", "details");
		Map<String,String[]> userIdInGroupMap = new HashMap<>();
		map.forEach((key, arr) -> {
			if (userIdList.contains(key))
				userIdInGroupMap.put(key, arr);
		});
		model.addAttribute("map", userIdInGroupMap);
		model.addAttribute("routeList", routeList);
		return "statistics";
	}



	private void fill(Map<String, String[]> map, List<List<Map<String, String>>> list, int i) {
		list.get(i).stream().forEach(qmap -> {
			String pid = qmap.get("pid");
			if (map.containsKey(pid)) {
				String[] contentArr = map.get(pid);
				contentArr[i+2] = String.valueOf(qmap.get("count"));
			} else {
				//contentArr[0]为名字
				//contentArr[1]为汇总
				String[] contentArr = new String[7];
				contentArr[0] = qmap.get("fullname");
				contentArr[i+2] = String.valueOf(qmap.get("count"));
				map.put(pid, contentArr);
			}
		});
	}
	
	@RequestMapping("/detailStatistics")
	public String detailStatistics(String beginDate, String endDate, String userId, @RequestParam(defaultValue="1") Integer pageNo, Model model) {
		PageHelper.startPage(pageNo, DEFAULT_COUNT);
		List<Demand> demandList = demandService.detailStatistics(beginDate, endDate, userId);
		PageInfo<Demand> pageInfo = new PageInfo<>(demandList);
		List<User> userList = userService.queryInPidList(pageInfo.getList().stream().map(Demand::getCollectPersonId).distinct().collect(Collectors.toList()));
		pageInfo.getList().forEach(demand -> {
			demand.setCollectPersonId(userList.stream().filter(user -> demand.getCollectPersonId().equals(user.getPid())).map(User::getFullName).findAny().get());
			setDemandWorth(demand);
		});
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("pageInfo_demand", true);
		model.addAttribute("route", "/demand");
		return "detailStatistics";
	}
	
	/**
	 * 查找同名的需求
	 * @author pdz
	 * @date 2018年11月7日
	 * @param projectName
	 * @return
	 */
	@RequestMapping("/checkName")
    @ResponseBody
    public List<Demand> checkName(String demandName) {
		Demand demand = new Demand();
		demand.setDemandName(demandName);
    	List<Demand> demandList = demandService.queryAll(demand);
    	demandList.forEach(dem -> {
    		dem.setDemandType(getDicCheckboxWorth(dem.getDemandType(), Constant.DICTIONTRY_DEMANDTYPE)); 
    		dem.setDemandStatusWorth(getDicSingleWorth(dem.getDemandStatus(), Constant.DICTIONTRY_DEMANDSTATUS));
    	});
		return demandList;
    }
	
	@RequestMapping("/showSelf")
    public String showSelf(HttpServletRequest request) {
    	return "redirect:/demand/showConditionQuery?collectPersonId="+getUserId(request);
    }
	
	@RequestMapping("/updateDetailStatistics")
    public String updateDetailStatistics(String beginDate, String endDate, String userId, Integer operaIndex, String fullname, @RequestParam(defaultValue="1") Integer pageNo, Model model) {
    	List<String> refPidList = queryUpdateLog(beginDate, endDate, userId, operaIndex);
    	PageHelper.startPage(pageNo, DEFAULT_COUNT);
		List<Demand> demandList = demandService.queryInPidList(refPidList);
		PageInfo<Demand> pageInfo = new PageInfo<>(demandList);
		pageInfo.getList().forEach(demand -> {
			demand.setCollectPersonId(fullname);
			setDemandWorth(demand);
		});
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("pageInfo_demand", true);
		model.addAttribute("route", "/demand");
		return "detailStatistics";
    }
	
}
